package net.vinote.sosa.rpc.netty.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.AttributeKey;
import net.vinote.sosa.rpc.RpcConfig;
import net.vinote.sosa.rpc.RpcConstant;
import net.vinote.sosa.rpc.RpcResponse;
import net.vinote.sosa.rpc.Session;
import net.vinote.sosa.rpc.channel.ClientChannelService;
import net.vinote.sosa.rpc.netty.NettySession;
import net.vinote.sosa.rpc.netty.RpcChannelHandler;
import net.vinote.sosa.rpc.netty.RpcDecoder;
import net.vinote.sosa.rpc.netty.RpcEncoder;
import net.vinote.sosa.rpc.process.DisruptorProcessor;
import net.vinote.sosa.rpc.process.MessageProcessor;

public class RpcNettyClient implements ClientChannelService {
	private Session session;
	private EventLoopGroup workerGroup = new NioEventLoopGroup();
	private MessageProcessor<RpcResponse> processor;

	@Override
	public <T> void start(RpcConfig config, MessageProcessor<T> process) throws Exception {
		final MessageProcessor<RpcResponse> processor = (MessageProcessor<RpcResponse>) process;

		Bootstrap b = new Bootstrap(); // (1)
		b.group(workerGroup); // (2)
		b.channel(NioSocketChannel.class); // (3)
		b.option(ChannelOption.SO_KEEPALIVE, true); // (4)
		//b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.getTimeout());
		b.handler(new ChannelInitializer<SocketChannel>() {
			@Override
			public void initChannel(SocketChannel ch) throws Exception {
				ch.pipeline().addLast(new RpcDecoder(), new RpcChannelHandler<RpcResponse>(processor))
					.addLast(new RpcEncoder());
			}
		});

		// Start the client.
		ChannelFuture channel = b.connect(config.getHost(), config.getPort()).sync(); // (5)
		session = new NettySession(channel.channel(),config);
		channel.channel().attr(AttributeKey.valueOf(RpcConstant.SESSION_KEY)).set(session);

	}

	public void start(final RpcConfig config) throws Exception {
		processor = new DisruptorProcessor<RpcResponse>();
		processor.init(config);
		start(config, processor);
	}

	/**
	 * Getter method for property <tt>session</tt>.
	 *
	 * @return property value of session
	 */
	public Session getSession() {
		return session;
	}

	public void shutdown() {
		try {
			session.close();
		} finally {
			workerGroup.shutdownGracefully();
		}
		if (processor != null) {
			processor.shutdown();
		}
	}

}